<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { login } from "@/api";
import socket from "@/utils/socket";

const router = useRouter();

const loginForm = reactive({
  userName: "",
  password: "",
});

const rules = {
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const loginFormRef = ref(null);
const loading = ref(false);

const handleLogin = async () => {
  try {
    const valid = await loginFormRef.value.validate();
    if (valid) {
      loading.value = true;
      const res = await login(loginForm);
      localStorage.setItem("imtoken", res.token);
      localStorage.setItem("serviceImKey", res.imKey);
      localStorage.setItem("imUserInfo", JSON.stringify(res.userInfo));

      // 登录成功后立即连接 Socket
      const SOCKET_URL = import.meta.env.VITE_SOCKET_URL;
      socket.connect(SOCKET_URL, res.imKey);

      ElMessage.success("登录成功");
      router.push("/");
    }
  } catch (error) {
    console.error("登录失败：", error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h2>技能猴子客服系统</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="0"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  background-image: url("../assets/login-bg.png");
  background-size: cover;
  background-position: center;
  /* 背景模糊  */
  backdrop-filter: blur(20px);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
</style> 